﻿using System;
using System.Data;
using System.Reflection;

namespace EHSubmit.Util
{

    /// <summary>
    /// 对象帮助类，提供反射调用等功能
    /// </summary>
    public class ObjectHelper
    {
        /// <summary>
        /// 执行实例的指定方法 
        /// </summary>
        /// <param name="obj">实例</param>
        /// <param name="methodName">方法名</param>
        public static void ExecuteMethod(object obj, string methodName)
        {
            ExecuteMethod(obj, methodName, null);
        }

        /// <summary>
        /// 执行实例的指定方法 
        /// </summary>
        /// <param name="obj">实例</param>
        /// <param name="methodName">方法名</param>
        /// <param name="o">方法的参数列表</param>
        public static void ExecuteMethod(object obj, string methodName, object[] o)
        {
            try
            {
                Type type = obj.GetType();
                MethodInfo info = type.GetMethod(methodName);

                info.Invoke(obj, o);
            }
            catch (NullReferenceException nre)
            {
                LogHelper.Log(nre.Message, nre);

                throw new DynamicCallException();    // 重定义异常，面向高层
            }
            
        
        }

        /// <summary>
        /// 给实例相应的属性赋给定的属性值
        /// </summary>
        /// <param name="obj">实例</param>
        /// <param name="attrName">属性名</param>
        /// <param name="value">属性值</param>
        public static void SetAttr(object obj, string attrName, object value)
        {
            Type type = obj.GetType();
            PropertyInfo info = type.GetProperty(attrName);
            info.SetValue(obj, value, null);
        }
    }
}